package com.zeratul.common.feign.inter.web;

import cn.hutool.core.util.ObjectUtil;
import com.zeratul.common.core.constant.RemoteConstants;
import com.zeratul.common.core.context.DataContextHolde;
import com.zeratul.common.json.utils.JsonUtils;
import com.zeratul.web.interceptor.base.BaseHandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.Map;

/**
 * Feign请求的被调用方拦截器
 */
@Slf4j
public class FeignServerInterceptor extends BaseHandlerInterceptor {

    /**
     * 对于Feign请求的前置拦截处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceContext = request.getHeader(RemoteConstants.TRACE_CONTEXT);
        if (ObjectUtil.isNotEmpty(traceContext)) {
            //设置全局链路上下文数据
            DataContextHolde.setTraceContext(JsonUtils.deserialize(traceContext, Map.class));
        }

        String mdc = request.getHeader(RemoteConstants.MDC);
        if (ObjectUtil.isNotEmpty(mdc)) {
            //设置全局MDC上下文数据
            MDC.setContextMap(JsonUtils.deserialize(mdc, Map.class));
        }
        return true;
    }

    /**
     * 后置拦截器
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        DataContextHolde.clear();
        MDC.clear();
    }

    /**
     * 拦截器的拦截Path路径
     *
     * @return
     */
    @Override
    public String path() {
        return "/inner/**";
    }
}
